package com.rr.learningdemo.flink;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;

/**
 * @author RR
 * @date 2021/7/12 23:33
 */
public class RichMapFunctionTest {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //从txt文件读取数据
        String txtFilePath = "G:\\IDEAProject\\learning-demo\\src\\main\\resources\\WordCount.txt";
        DataSource<String> stringDataSource = env.readTextFile(txtFilePath);
        //批处理用dataSet，流处理用dataStream
        DataSet<Tuple2<String, Integer>> sum = stringDataSource.flatMap(new WordCountDataSet.MyFlatMapper())
                .groupBy(0) //按照tuple2的0号下标分组
                .sum(1);//按照tuple2的1号下标求和
        MapOperator<Tuple2<String, Integer>, String> map = sum.map(new MyRichMapFunction());
        map.print();
        sum.print();

    }

    //RichMapFunction，里面有很多一些方法可以重写、调用，下面重写个open和close
    static class MyRichMapFunction extends RichMapFunction<Tuple2<String, Integer>, String> {

        @Override
        public String map(Tuple2<String, Integer> tuple2) throws Exception {

            //这里有吧啦吧啦很多操作
//            getRuntimeContext();
//            getIterationRuntimeContext();

            return tuple2.f0 + tuple2.f1;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            //这里可以建立一些一次性的操作，比如连接数据库啥的
            //这个的执行次数跟设定的并行度一样多
            System.out.println("myRichMapFunction  open  ...");
        }

        @Override
        public void close() throws Exception {
            //这里可以关闭连接啥的
            System.out.println("myRichMapFunction  close  ...");
        }
    }
}
